package it.av.training.rest.service.web;

import it.av.training.rest.exception.ErrorCode;
import it.av.training.rest.exception.RestException;
import it.av.training.rest.models.User;
import it.av.training.rest.models.json.JSONResponse;
import it.av.training.rest.service.UserService;

import java.util.HashMap;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.wordnik.swagger.annotations.ApiOperation;

/**
 * Controller to push message
 * 
 * @author alessandro vincelli
 * 
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {

    private static Logger logger = Logger.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    @Qualifier("messageSource")
    private ReloadableResourceBundleMessageSource messages;

    /**
     * @param user
     * @return added user
     */
    @ApiOperation(value = "Add a new user", notes = "To Add a new user pass it as request Body.", responseClass = "JSONResponse")
    @RequestMapping(method = { RequestMethod.POST })
    public JSONResponse addUser(@RequestBody User user) {
        JSONResponse response = new JSONResponse(JSONResponse.SUCCESS, "000", "user added");
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("user", userService.addUser(user));
        response.setData(map);
        return response;
    }

    /**
     * @param userID
     */
    @ApiOperation(value = "Delete a user", notes = "", responseClass = "JSONResponse")
    @RequestMapping(value = "/{userID}", method = { RequestMethod.DELETE })
    public void removeUser(@PathVariable String userID) {
        userService.removeUser(userID);
    }

    /**
     * @param user
     * @return modified user
     */
    @ApiOperation(value = "Modifiy an existing user", notes = "", responseClass = "JSONResponse")
    @RequestMapping(method = { RequestMethod.PUT })
    public JSONResponse editUser(@RequestBody User user) {
        JSONResponse response = new JSONResponse(JSONResponse.SUCCESS, "000", "user added");
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("user", userService.editUser(user));
        response.setData(map);
        return response;
    }

    /**
     * @param userID
     * @return user
     */
    @ApiOperation(value = "Return user", notes = "Return a user with the given ID", responseClass = "JSONResponse")
    @RequestMapping(value = "/{userID}", method = { RequestMethod.GET })
    public JSONResponse getUser(@PathVariable String userID) {
        JSONResponse response = new JSONResponse(JSONResponse.SUCCESS, "000", "OK");
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("user", userService.getUser(userID));
        response.setData(map);
        return response;
    }

    /**
     * Gestisce le eccezioni
     * 
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ModelAndView handleIOException(Exception ex) {
        ModelAndView modelAndView = new ModelAndView();
        logger.error("Error on On User Contoller", ex);
        JSONResponse jsonResponse = new JSONResponse(JSONResponse.FAIL);
        if (ex instanceof RestException) {
            RestException ex2 = (RestException) ex;
            jsonResponse.setMessage(messages.getMessage(ex2.getErrorCode().getCode(), null, null));
            jsonResponse.setCode(ex2.getErrorCode().getCode());
        } else {
            jsonResponse.setMessage(ex.getMessage());
            jsonResponse.setCode(ErrorCode.ERRORE_GENERICO.getCode());
        }
        modelAndView.addObject("response", jsonResponse);
        return modelAndView;
    }
}
